import React, { useMemo } from 'react';

import { PixelProgressProps } from '../types';

/**
 * 像素风格进度条组件
 * 通过小方块拼接成像素风格的进度条
 */
const PixelProgress: React.FC<PixelProgressProps> = ({
  progress = 0,
  width = '100%',
  height = '20px',
  pixelSize = 4,
  pixelGap = 1,
  backgroundColor = '#f0f0f0',
  fillColor = '#4caf50',
  showPercentage = true,
  textColor = '#000',
  className = '',
  style = {},
  animationDuration = 300,
}) => {
  // 确保进度值在0-100之间
  const normalizedProgress = Math.min(100, Math.max(0, progress));

  // 计算像素网格
  const pixelGrid = useMemo(() => {
    // 计算容器尺寸
    const containerWidth =
      typeof width === 'number' ? width : parseInt(width) || 100;
    const containerHeight =
      typeof height === 'number' ? height : parseInt(height) || 20;

    // 计算水平和垂直方向的像素数量
    const horizontalPixels = Math.floor(
      containerWidth / (pixelSize + pixelGap),
    );
    const verticalPixels = Math.floor(containerHeight / (pixelSize + pixelGap));

    // 计算填充的像素数量
    const filledPixels = Math.floor(
      (horizontalPixels * normalizedProgress) / 100,
    );

    // 生成像素网格
    const grid = [];
    for (let y = 0; y < verticalPixels; y++) {
      for (let x = 0; x < horizontalPixels; x++) {
        grid.push({
          x,
          y,
          filled: x < filledPixels,
        });
      }
    }

    return grid;
  }, [width, height, pixelSize, pixelGap, normalizedProgress]);

  // 容器样式
  const containerStyle: React.CSSProperties = {
    position: 'relative',
    width,
    height,
    backgroundColor: 'transparent',
    overflow: 'hidden',
    ...style,
  };

  // 像素容器样式
  const pixelContainerStyle: React.CSSProperties = {
    position: 'relative',
    width: '100%',
    height: '100%',
    backgroundColor,
  };

  // 文本样式
  const textStyle: React.CSSProperties = {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    color: textColor,
    fontSize: '12px',
    fontWeight: 'bold',
    zIndex: 2,
  };

  return (
    <div className={`pixel-progress ${className}`} style={containerStyle}>
      <div className="pixel-progress-container" style={pixelContainerStyle}>
        {pixelGrid.map((pixel, index) => (
          <div
            key={index}
            className={`pixel ${pixel.filled ? 'filled' : ''}`}
            style={{
              position: 'absolute',
              left: `${pixel.x * (pixelSize + pixelGap)}px`,
              top: `${pixel.y * (pixelSize + pixelGap)}px`,
              width: `${pixelSize}px`,
              height: `${pixelSize}px`,
              backgroundColor: pixel.filled ? fillColor : 'transparent',
              transition: `background-color ${animationDuration}ms ease`,
            }}
          />
        ))}
      </div>
      {showPercentage && (
        <div className="pixel-progress-text" style={textStyle}>
          {`${Math.round(normalizedProgress)}%`}
        </div>
      )}
    </div>
  );
};

export default PixelProgress;
